package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.PageResult;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.dto.RoleDto;
import com.itheima.ydd.entity.SysRole;
import com.itheima.ydd.service.ISysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 角色表 前端控制器
 * </p>
 */
@RestController
@RequestMapping("/sys_role")
public class SysRoleController {
    @Autowired
    private ISysRoleService iSysRoleService;

    @GetMapping("allData")
    public ResultData all(){
        List<SysRole> list = iSysRoleService.list();
        return ResultData.ok("查询成功",list);
    }


    /**
     * 分页查询
     * @param page
     * @param limit
     * @param name
     * @return
     */
    @GetMapping("/list")
    public ResultData list(String name,int page,int limit){
        //构造分页构造器
        Page<SysRole> rolePage=new Page<>(page,limit);
        //构造条件查询器
        LambdaQueryWrapper<SysRole> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.like(name!=null,SysRole::getName,name);
        //执行分页查询
        iSysRoleService.page(rolePage,queryWrapper);

        return ResultData.ok("", PageResult.getPage(rolePage));
    }

    /**
     * 通过id回显需要修改的角色数据
     * @param id
     * @return
     */
    @GetMapping("rowInfo")
    public ResultData rowInfo(String id){
        RoleDto roleDto = iSysRoleService.getRole(id);
        return ResultData.ok("返回要修改的数据",roleDto);
    }
    @PostMapping("update")
    public ResultData update(@RequestBody RoleDto roleDto){
        roleDto.setUpdateDate(LocalDateTime.now());
        iSysRoleService.updateById(roleDto);
        List<String> menuids = roleDto.getMenuids();
        String id = roleDto.getId();
        iSysRoleService.updateMenu(menuids,id);
        return ResultData.ok("角色修改成功","");

    }

    @PostMapping("add")
    public ResultData add(@RequestBody RoleDto roleDto){
        roleDto.setCreateDate(LocalDateTime.now());
        iSysRoleService.saveWithMenu(roleDto);
        return ResultData.ok("角色添加成功","");
    }

    @GetMapping("/del")
    public ResultData del(String id){
       iSysRoleService.del(id);
       return ResultData.ok("删除角色成功","");
    }
}
